﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AIS.SDK.Api.Response;
using AIS.SDK.Handler;
using AIS.SDK.Model;
using AISservice.Common;
using AISservice.Entity;
using Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace AISservice.Controllers
{
    [Route("api/v1/[controller]/[action]")]
    [ApiController]
    public class P42040Controller : ControllerBase
    {

        /// <summary>
        /// 审批NR单到540
        /// </summary>
        /// <param name="objparam"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<MQResponse> UpdateNextState(dynamic objparam)
        {
            Log4Net.Debug(objparam);
            Console.WriteLine(objparam);
            //用了新的方式，哈哈方便多了
            P42040Param param = Common.JsonHelper.JsonToObject<P42040Param>(((Newtonsoft.Json.Linq.JObject)objparam).ToString());
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            int stackId = 0;
            int stateId = 0;
            string rid = "";
            string token = "";
            bool needclose = false;


            string applicaton = "P42040";
            string formname = "W42040A";
            string version = "MBR001R";

            try
            {
                if (string.IsNullOrWhiteSpace(param.username) || string.IsNullOrWhiteSpace(param.password))
                {
                    throw new Exception("请求的用户名或密码为空！");
                }

                token = SomeHandler.GetToken(param.username, param.password);

                if (string.IsNullOrWhiteSpace(token))
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");


                Console.WriteLine($"{DateTime.Now.ToString()} 查找NR单据 {param.NROrderno}");

                FormRequest formRequest = new FormRequest()
                {
                    //maxPageSize = "2",
                    //returnControlIDs = "1[10,11,12,43,41]",
                    formName =$"{applicaton}_{formname}", //"P42040_W42040A",
                    version =version, //"MBR001R",
                    formServiceAction = "R",
                    bypassFormServiceEREvent = true,
                    formActions = new FormActionsCollection
                                 (
                                     new FSREvent[]
                                     {
                                      new FSREvent() { controlID="13", command="SetControlValue" ,value=param.NROrderno },
                                      new FSREvent() { controlID="46", command="DoAction"  }
                                     }
                                 )
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    action = "open",
                    outputType = "VERSION2",
                    formName = $"{applicaton}_{formname}",//"P42040_W42040A",
                    stackId = stackId,
                    stateId = stateId,
                    formRequest = formRequest
                };
                AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                //Console.WriteLine(response.JsonString);
                stackId = response.stackId;
                stateId = response.stateId;
                rid = response.rid;
                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P42040_W42040A"))
                {
                    JObject obj = response.ToJObject();
                    int rowcount = Convert.ToInt16(obj["fs_P42040_W42040A"]["data"]["gridData"]["summary"]["records"]);
                    Console.WriteLine($"查询到{rowcount }条记录");
                    List<gridrowupdateevents> gridrows = new List<gridrowupdateevents>();
                    List<gridcolumnevent> gridcols = new List<gridcolumnevent>();
                    for (int i = 0; i < rowcount; i++)
                    {
                        Console.WriteLine($"正在处理第{i}行 ");
                        stackId = response.stackId;
                        stateId = response.stateId;
                        int rowindex = Convert.ToInt32(obj["fs_P42040_W42040A"]["data"]["gridData"]["rowset"][i]["rowIndex"]);
                        gridcols.Add(new gridcolumnevent()
                        {
                            columnID = "1",
                            command = "ClickGridCell"
                        });
                        gridrows.Add(new gridrowupdateevents()
                        {
                            gridColumnEvents = gridcols,
                            rowNumber = rowindex
                        });

                    }

                    ActionRequest actionRequest = new ActionRequest()
                    {
                        //returnControlIDs = "1[348,440,257,45,46,47,48,49,50,51]",
                        formOID = "W42040A",
                        formActions = new FormActionsCollection
                                    (
                                        new FSREvent[]
                                        {
                                          new FSREvent() { controlID="1", command="SelectAllRows" 
                                             //, gridAction =new GridAction(){gridID="1",gridRowUpdateEvents=gridrows }
                                          },
                                          new FSREvent() { controlID="4", command="DoAction"  }
                                        }
                                    )
                                ,
                        stopOnWarning = "false"
                    };
                    asrequest = new ApplicationStackRequest()
                    {
                        outputType = "VERSION2",
                        allowCache = false,
                        action = "execute",
                        actionRequest = actionRequest,
                        stackId = response.stackId,//上一次返回的值
                        stateId = response.stateId,
                        rid = response.rid
                    };

                    response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                    needclose = true;
                    stackId = response.stackId;
                    stateId = response.stateId;
                    rid = response.rid;
                    if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P42040_W42040A"))
                    {

                        obj = response.ToJObject();
                        //应该查询到数据
                        //string NAno = obj["fs_P58E4210_W58E4210E"]["data"]["gridData"]["rowset"]["0"]["z_DOCO_45"].ToString();
                        execresult.Result = param.NROrderno;
                        execresult.Message = response.JsonString;
                        Log4Net.Info(response.JsonString);
                        Console.WriteLine($"{DateTime.Now.ToString()} {param.NROrderno}审核完成:   {response.currentApp}");
                    }
                }

            }
            catch (MQException x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", x.ExceptionCode).ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
            }
            finally
            {
                #region Close

                ActionRequest actionRequest = new ActionRequest()
                {
                    //returnControlIDs = "1[17,18,19,20]",
                    formOID = "W42040A"
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    outputType = "VERSION2",
                    allowCache = true,
                    action = "close",
                    actionRequest = actionRequest,
                    stackId = stackId,//上一次返回的值
                    stateId = stateId,
                    rid = rid
                };
                if (!string.IsNullOrWhiteSpace(token) && needclose)
                {
                    AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                    //Console.WriteLine(response.JsonString);
                }
                #endregion
            }

            return execresult;
        }

    }
}